import { IconCamera, IconPlayCircle, IconDownload, IconStop } from "@douyinfe/semi-icons";
import { Button } from "@douyinfe/semi-ui";
import { useState, useRef, useEffect } from "react";

const constraints = {
  audio: false,
  video: {
    width: 480,
    height: 320,
    frameRate: 30,
  },
};

const Record = () => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const videoPlayRef = useRef<HTMLVideoElement>(null);

  const [recoding, setRecoding] = useState(false);
  const [canPlay, setCanPlay] = useState(false);

  const [mediaStream, setMediaStream] = useState<MediaStream>();
  const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder>();

  const [dataBuffer, setDataBuffer] = useState<Blob[]>([]);

  useEffect(() => {
    navigator.mediaDevices.getUserMedia(constraints).then((mediaStream) => {
      setMediaStream(mediaStream);
      if (videoRef.current) {
        videoRef.current.srcObject = mediaStream;
      }
    });
  }, []);

  const handleDataAvailable = (e: BlobEvent) => {
    if (e && e.data && e.data.size > 0) {
      setDataBuffer([...dataBuffer, e.data]);
    }
  };

  const startCapture = () => {
    setRecoding(true);
    setCanPlay(false);
    setDataBuffer([]);
    if (mediaStream) {
      const option = {
        mimeType: "video/webm;codecs=vp8",
      };
      if (!MediaRecorder.isTypeSupported(option.mimeType)) {
        console.error(`mime type 不支持: ${option.mimeType}`);
        return;
      }
      const mediaRecorder = new MediaRecorder(mediaStream, option);
      setMediaRecorder(mediaRecorder);

      mediaRecorder.ondataavailable = handleDataAvailable;
      mediaRecorder.start();
    }
  };

  const stopCapture = () => {
    setRecoding(false);
    setCanPlay(true);
    mediaRecorder?.stop();
  };

  const playVideo = () => {
    const blob = new Blob(dataBuffer, { type: "video/webm;codecs=vp8" });
    if (videoPlayRef.current) {
      videoPlayRef.current.src = window.URL.createObjectURL(blob);
      videoPlayRef.current.srcObject = null;
      videoPlayRef.current.controls = true;
      videoPlayRef.current.play();
    }
  };

  const downloadVideo = () => {
    const blob = new Blob(dataBuffer, { type: "video/webm;codecs=vp8" });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.style.display = "none";
    a.download = "video.webm";
    a.click();
  };

  return (
    <div>
      <h1>Record</h1>
      <div className="flex justify-start">
        <video ref={videoRef} autoPlay playsInline></video>
        <video ref={videoPlayRef} playsInline></video>
      </div>
      <div className="w-1/3 flex justify-around mt-10">
        {recoding ? (
          <Button theme="solid" type={"danger"} size={"large"} icon={<IconStop />} onClick={stopCapture}>
            停止
          </Button>
        ) : (
          <Button theme="solid" size={"large"} icon={<IconCamera />} onClick={startCapture}>
            录制
          </Button>
        )}
        <Button onClick={playVideo} disabled={!canPlay} theme="solid" size={"large"} icon={<IconPlayCircle />}>
          播放
        </Button>
        <Button onClick={downloadVideo} disabled={!canPlay} theme="solid" size={"large"} icon={<IconDownload />}>
          下载
        </Button>
      </div>
    </div>
  );
};

export default Record;
